$(function() {
    //个人资料
    var uid = $("#login_user_id").val();
    profile(uid);

    //下述需要在JS运行之前形成，因此采用服务器端写入；
    //好友列表

    //喜爱列表

    //申请列表
    applyList();
    //聊天列表


});



//聊天列表
function chatList() {
  $.post("/chat/item/list", {},
  function(o) {
    if (o.code == 200) {
      var list = o.data;
      $.each(list,
      function(i, d) {
        var html = '';
        if (i == 0) {
          html += '<li class="list-group-item active-chat">';
        } else {
          html += '<li class="list-group-item">';
        }
        if (d.onlineStatus) {
          html += '<figure class="avatar avatar-state-success">';
        } else {
          html += '<figure class="avatar">';
        }
        if (d.pic == null || d.pic == "") {
          var str = d.nickname;
          var s = str.substring(0, 1);
          html += '<span class="avatar-title bg-info rounded-circle">' + s + '</span>';
        } else {
          html += '<img src="' + d.pic + '" class="rounded-circle" alt="image">';
        }

        html += '</figure>';
        html += '<div class="users-list-body">';
        html += 'div>';
        if (d.favorite == 1) {
          html += '<h5 class="text-primary">' + d.nickname + '</h5>';
        } else {
          html += '<h5>' + d.nickname + '</h5>';
        }

        html += '<p>' + d.description + '</p>';
        html += '</div>';
        html += '<div class="users-list-action">';
        if (d.notReadCnt > 0) {
          html += '<div class="new-message-count">' + d.notReadCnt + '</div>';
          if (d.favorite == 1) {
            html += '<small class="text-primary">' + d.lastMsgArriveTime + '</small>';
          } else {
            html += '<small class="text-muted">' + d.lastMsgArriveTime + '</small>';
          }
        } else {
          html += '<small class="text-muted">' + d.lastMsgArriveTime + '</small>';
          html += '<div class="action-toggle">';
          html += '<div class="dropdown">';
          html += '<a data-toggle="dropdown" href="#"><i data-feather="more-horizontal"></i></a>';
          html += '<div class="dropdown-menu dropdown-menu-right">';
          html += '<a href="#" class="dropdown-item btn-open-chat">Open</a>';
          html += '<a href="#" data-navigation-target="contact-information" class="dropdown-item">Profile</a>';
          html += '<a href="#" class="dropdown-item">Add to archive</a>';
          html += 'div class="dropdown-divider"></div>';
          html += '<a href="#" class="dropdown-item text-danger">Delete</a>';
          html += '</div>';
          html += '</div>';
          html += '</div>';
        }
        html += '</div>';
        html += '</div>';
        html += '</li>';
        $("#chat-list").append(html);
      });
    } else {
      alert(o.msg);
    }
  });
}

//好友列表
function friendList() {
  $.post("/chat/friend/list", {},
  function(o) {
    if (o.code == 200) {
      var list = o.data;
      var cnt = o.data.length;
      $("#friend-cnt").text(cnt + ' Friends');
      $.each(list,
      function(i, d) {
        var html = '<li class="list-group-item">';
        html += '<div>';
        if (d.onlineStatus) {
          html += '<figure class="avatar avatar-state-success">';
        } else {
          html += '<figure class="avatar">';
        }
        if (d.pic == null || d.pic == "") {
          var str = d.nickname;
          var s = str.substring(0, 1);
          html += '<span class="avatar-title bg-info rounded-circle">' + s + '</span>';
        } else {
          html += '<img src="' + d.pic + '" class="rounded-circle" alt="image">';
        }
        html += '</figure></div>';
        html += '<div class="users-list-body">';
        html += '<div><h5>' + d.remark + '</h5><p>' + d.nickname + '</p></div>';
        html += '<div class="users-list-action">';
        html += '<div class="action-toggle">';
        html += '<div class="dropdown">';
        html += '<a data-toggle="dropdown" href="#"><i data-feather="more-horizontal"></i></a>';
        html += '<div class="dropdown-menu dropdown-menu-right">';
        html += '<a href="#" class="dropdown-item">New chat</a>';
        html += '<a href="#" data-navigation-target="contact-information" class="dropdown-item">Profile</a>';
        html += '<div class="dropdown-divider"></div>';
        html += '<a href="#" class="dropdown-item text-danger">Block</a>';
        html += '</div></div></div></div></div></li>';
        $("#friend-list").append(html);
      });
    } else {
      alert(o.msg);
    }
  });
}

//新建聊天-选择好友列表
function newChatList() {
  $.post("/chat/friend/list", {},
  function(o) {
    if (o.code == 200) {
      var list = o.data;
      $.each(list,
      function(i, d) {
        var html = '<li class="list-group-item">';
        html += '<div>';
        if (d.onlineStatus) {
          html += '<figure class="avatar avatar-state-success">';
        } else {
          html += '<figure class="avatar">';
        }
        if (d.pic == null || d.pic == "") {
          var str = d.nickname;
          var s = str.substring(0, 1);
          html += '<span class="avatar-title bg-info rounded-circle">' + s + '</span>';
        } else {
          html += '<img src="' + d.pic + '" class="rounded-circle" alt="image">';
        }
        html += '</figure></div>';
        html += '<div class="users-list-body">';
        html += '<div><h5>' + d.remark + '</h5><p>' + d.nickname + '</p></div>';
        html += '<div class="users-list-action">';
        html += '<div class="action-toggle">';
        html += '<div class="dropdown">';
        html += '<a data-toggle="dropdown" href="#"><i data-feather="more-horizontal"></i></a>';
        html += '<div class="dropdown-menu dropdown-menu-right">';
        html += '<a href="#" class="dropdown-item">New chat</a>';
        html += '<a href="#" data-navigation-target="contact-information" class="dropdown-item">Profile</a>';
        html += '<div class="dropdown-divider"></div>';
        html += '<a href="#" class="dropdown-item text-danger">Block</a>';
        html += '</div></div></div></div></div></li>';
        $("#new-chat-list").append(html);
      });
    } else {
      alert(o.msg);
    }
  });
}

//特别好友列表
function favorite() {
  $.post("/chat/friend/favoriteList", {},
  function(o) {
    if (o.code == 200) {
      var list = o.data;
      $.each(list,
      function(i, d) {
        var html = '<li class="list-group-item">';
        html += '<div class="users-list-body">';
        html += '<div><h5>' + d.remark + '</h5><p>' + d.nickname + '</p></div>';
        html += '<div class="users-list-action">';
        html += '<div class="action-toggle">';
        html += '<div class="dropdown">';
        html += '<a data-toggle="dropdown" href="#"><i data-feather="more-horizontal"></i></a>';
        html += '<div class="dropdown-menu dropdown-menu-right">';
        html += '<a href="#" class="dropdown-item btn-open-chat">Open</a>';
        html += '<a href="#" class="dropdown-item">Remove favorites</a>';
        html += '</div>';
        html += '</div></div></div></div></li>';
        $("#favorite-list").append(html);
      });
    } else {
      alert(o.msg);
    }
  });
}

//归档聊天列表


//个人信息
function profile(id) {
  $.get("/chat/friend/profile/" + id,
  function(res) {
    var obj = res.data;
    var html = '';
    if (obj.pic == null || obj.pic == "") {
      var str = obj.nickname;
      var s = str.substring(0, 1);
      html = '<span class="avatar-title bg-info rounded-circle">' + s + '</span>';
    } else {
      html = '<img src="' + obj.pic + '" class="rounded-circle" alt="image">';
    }
    $("#info_pic").html(html);
    $("#info_name").text(obj.nickname);
    $("#info_last_login_ts").text("Last Login:"+obj.lastLoginStr);
    $("#info_description").text(obj.description);
    $("#info_account").text(obj.account);
    $("#info_homeAddress").text(obj.homeAddress);
    $("#info_city").text(obj.city);
    $("#info_hobby").text(obj.hobby);
    //edit-form
    var uid = $("#login_user_id").val();
    if( id == uid ){
        $("#edit_nickname").val(obj.nickname);
        $("#edit_customFile_url").val(obj.pic);
        $("#edit_customFile_image").attr('src',obj.pic);
        $("#edit_city").val(obj.city);
        $("#edit_sex").val(obj.sex);
        $("#edit_homeAddress").val(obj.homeAddress);
        $("#edit_about-text").val(obj.description);
        var hobby = obj.hobby;
        var hbs = document.getElementsByName("edit_hobby");
        for(var i=0;i<hbs.length;i++){
            var v1 = hbs[i].value;
            if(hobby.search(v1) != -1){
                hbs[i].checked = true;
            }
        }
    }
  });
}


//修改资料
function editProfile(){
    var uid = $("#login_user_id").val();

    var nickname = $("#edit_nickname").val();
    var pic = $("#edit_customFile_url").val();
    var city = $("#edit_city").val();

    var sex = $("#edit_sex").val();
    var homeAddress = $("#edit_homeAddress").val();
    var description = $("#edit_about-text").val();
    var hobbies = document.getElementsByName("edit_hobby");
    var hobby=new Array();
    for(var i=0;i< hobbies.length;i++){
        if(hobbies[i].checked == true){
            hobby.push(hobbies[i].value)
        }
    }
    var data = {"nickname":nickname,"pic":pic,"sex":sex,"city":city,
        "homeAddress":homeAddress,"description":description,"hobby":hobby.toString()};
    $.post("/chat/friend/edit-profile",data,function(res){
        alert("已修改")
        profile(uid);
    });
}

//上传头像
function editPic(){
    var uid = $("#login_user_id").val();
    var files = $("#edit_customFile").prop('files');
    var url = URL.createObjectURL(files[0]);
    $("#edit_customFile_image").attr('src',url);
    var form = new FormData();
        form.append('uid', uid);
        form.append('file', files[0]);
    $.ajax({
        url:'/chat/friend/up-pic',
        type: 'post',
        processData: false,
        contentType: false,
        data: form,
        success: function(res){
            console.log(res)
            if( res.code == 200 ){
                $("#edit_customFile_url").val(res.data);
                $("#edit_customFile_image").attr('src',res.data);
            }
        }
    });
}

//申请好友
function applyNew(){
    var email = $("#new_email").val();
    var msg = $("#new_message").val();
    var data={"email":email,"message":msg};
    $.post("/chat/friend/apply_new",data,function(res){
        alert("Send apply");
    });
}

//申请好友列表
function applyList(){
    $.post("/chat/friend/apply_me",function(res){
        console.log(res);
        var list = res.data;
        for(var i = 0;i<list.length;i++){
            appendApplyDiv(list[i]);
        }
    });
}

//审核
function audit(id){
    if(confirm("Agree friend apply?")){
        $.post("/chat/friend/audit",{"id":id,"status":1});
    }else{
        $.post("/chat/friend/audit",{"id":id,"status":0});
    }
}

//修改备注



//聊天记录-id是好友的id
function msgList(id) {
  $.post("/chat/message/list/" + id, {},
  function(o) {
    if (o.code == 200) {
      var list = o.data;
      if (list == null || list.length == 0) {
        $("#msg-show-none").show();
        $("#msg-show").hide();
      } else {
        $("#msg-show").show();
        $("#msg-show-none").hide();
        $.each(list,function(i, d) {
            appendNewMsg(d,id)
        });
        $("#msg-show").html(html);
      }
    } else {
      alert(o.msg);
    }
  });
}

//发送消息
function sendMsg() {
  var type = "text";
  var content = $("#msg_content").val();
  var sender = $("#login_user_id").val();
  var receiver = $("#receiver_id").val();
  if (content != "") {
    var obj = {
      "type": type,
      "content": content,
      "sender": sender,
      "receiver": receiver
    };
    $.post("/chat/msg/send",obj,function(res){
        var id = res.data;
        $.get("/chat/message/view/"+id,function(res){
            var d = res.data;
            appendNewMsg(d, receiver);
        });
    });
  }
}

//聊天内容-追加
function appendNewMsg(d, id) {
	var html = '';
	if (d.sender == id) {
		html += '<div class="message-item">';
	} else {
		html += '<div class="message-item outgoing-message">';
	}
	html += '    <div class="message-avatar">';
	html += '        <figure class="avatar" title="' + d.senderName + '">';
	if (d.sender == id) {
		if (d.pic == null || d.pic == "") {
			var str = d.senderName;
			var s = str.substring(0, 1);
			html += '<span class="avatar-title bg-info rounded-circle">' + s + '</span>';
		} else {
			html += '<img src="' + d.pic + '" class="rounded-circle" alt="image">';
		}
	} else {
		var selfPic = $("#selfPic").attr('src');
		html += '<img src="' + selfPic + '" class="rounded-circle" alt="image">';
	}

	html += '        </figure>';
	html += '    </div>';
	html += '    <div>';
	if (d.type == "text") {
		html += '        <div class="message-content">' + d.content + '</div>';
	}
	if (d.type == "image") {
		html += '        <div class="message-content message-image"><img src="' + d.linkId + '" class="rounded" alt="image"></div>';
	}
	if (d.type == "file") {
		html += '<div class="file-icon"><i class="fa fa-file"></i></div>';
		html += '<div>';
		html += '<div>' + d.fileName + '<i class="text-muted small">(' + d.fileSizeStr + ')</i></div>';
		html += '<ul class="list-inline"><li class="list-inline-item mb-0"><a href="' + d.linkId + '">Download</a></li></ul>';
		html += '</div>';
	}
	html += '        <div class="time">' + d.msgTime + '<i class="ti-double-check text-info"></i></div>';
	html += '   </div>';
	html += '</div>';
	$("#msg-show").append(html);
}

function appendApplyDiv(d){
    var html = '';
    html += '<li class="list-group-item">';
    html += '<figure class="avatar">';
	if (d.pic == null || d.pic == "") {
	    var str = d.nickname;
		var s = str.substring(0, 1);
		html += '<span class="avatar-title bg-info rounded-circle">' + s + '</span>';
	} else {
		html += '<img src="' + d.pic + '" class="rounded-circle" alt="image">';
	}
    html += '</figure>';
    html += '<div class="users-list-body">';
    html += '<div><h5>'+d.nickname+'</h5><p>'+d.message+'</p></div>';
    html += '<div class="users-list-action">';
    html += '<div class="action-toggle">';
    html += '<div class="dropdown">';
    html += '<a data-toggle="dropdown" href="#"><i data-feather="more-horizontal"></i></a>';
    html += '<div class="dropdown-menu dropdown-menu-right">';
    html += '<a href="#" class="dropdown-item btn-open-chat">Agree</a>';
    html += '<a href="#" class="dropdown-item">Ignore</a>';
    html += '<div class="dropdown-divider"></div>';
    html += '<a href="#" class="dropdown-item text-danger">Reject</a>';
    html += '</div></div></div></div></div></li>';
    $("#applies_list").append(html);
}